package com.lagou.edu.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @ClassName: MyLocaleResovel
 * @Auther: Jerry
 * @Date: 2020/7/22 16:11
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Configuration
public class MyLocaleResovel implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String local = request.getParameter("local");
        String header = request.getHeader("Accept-Language");
        Locale locale = null;

        if (StringUtils.isNotBlank(local)) {
            String[] locals = local.split("_");
            locale = new Locale(locals[0], locals[1]);
        } else {
            //zh-CN,zh;q=0.9
            String[] splits = header.split(",");
            String[] split = splits[0].split("-");
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResovel();
    }
}
